/**
 * Copyright 2018 lenos
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jantd.modules.activiti.controller;

import cn.jantd.core.api.vo.Result;
import cn.jantd.core.system.vo.LoginUser;
import cn.jantd.modules.activiti.entity.*;
import cn.jantd.modules.activiti.extract.CommonUtil;
import cn.jantd.modules.activiti.extract.EntityWrapper;
import cn.jantd.modules.activiti.service.*;
import cn.jantd.modules.system.entity.SysTeam;
import cn.jantd.modules.system.service.ISysTeamService;
import cn.jantd.modules.system.service.ISysUserRoleService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.ExtensionAttribute;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.*;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.TaskQuery;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhuxiaomeng
 * @date 2018/1/21.
 * @email 154040976@qq.com
 * <p>
 * 请假流程示例
 */
@Controller
@RequestMapping("/act/process/")
public class ProcessController {

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    HistoryService historyService;

    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    IProcessService processService;

    @Autowired
    ISysUserRoleService roleUserService;
    @Autowired
    IModelService modelService;

    @Autowired
    IdentitylinkService identitylinkService;

    @Autowired
    private ISysTeamService sysTeamService;

    @Autowired
    private IActIdMembershipService iActIdMembershipService;
    @Autowired
    private ITaskFileTypeService iTaskFileTypeService;

    @ResponseBody
    @GetMapping(value = "list")
    public Object list(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, ProcessInfo info) {
        String userId = CommonUtil.getUser().getId();
        info.setUserId(userId);
        long count = processService.count();
        QueryWrapper<ProcessInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("user_id", userId)
                .orderByDesc("create_time");
        List<ProcessInfo> processList = processService.list(queryWrapper);
        for (ProcessInfo process : processList) {
            if (process.getStatus() == 0) {
                process.setTaskName("未开始");
                continue;
            } else if (process.getStatus() != ProcessInfo.status_submit) {
                process.setTaskName("已结束");
                continue;
            }
            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(process.getProcessInstanceId()).singleResult();
            //保证运行ing
            if (instance == null) {
                process.setTaskName("已结束");
                continue;
            }
            TaskQuery query = this.taskService.createTaskQuery().processInstanceId(process.getProcessInstanceId());

            List<org.activiti.engine.task.Task> list = query.list();

//            org.activiti.engine.task.Task task = query.singleResult();
//            taskService.getVariable(task.getId(), ProcessInfo.variables_need_finish);

            for (int i = 0; i < list.size(); i++) {
//                process.setTaskName(task.getName());
                process.setTaskName(list.get(i).getName());
            }


        }
        Result result = new Result();
        result.setResult(new Page().setTotal(count).setRecords(processList));
        return result;
    }

    /**
     * 流程定义
     */
    @ResponseBody
    @GetMapping(value = "definition/list")
    public Object deploymentList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, cn.jantd.modules.activiti.entity.ProcessDefinition definition) {
        Result<IPage<cn.jantd.modules.activiti.entity.ProcessDefinition>> result = new Result<IPage<cn.jantd.modules.activiti.entity.ProcessDefinition>>();
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        if (definition != null) {
            if (!StringUtils.isEmpty(definition.getCategory())) {
                definitionQuery.deploymentId(definition.getDeploymentId());
            }
            if (!StringUtils.isEmpty(definition.getName())) {
                definitionQuery.processDefinitionNameLike("%" + definition.getName() + "%");

            }
        }
        List<cn.jantd.modules.activiti.entity.ProcessDefinition> definitionList = new ArrayList<>();
        List<org.activiti.engine.repository.ProcessDefinition> list = definitionQuery.listPage(Integer.valueOf(pageSize) * (Integer.valueOf(pageNo) - 1), Integer.valueOf(pageSize));
        list.forEach(each -> definitionList.add(new cn.jantd.modules.activiti.entity.ProcessDefinition(each)));
        long count = repositoryService.createDeploymentQuery().count();
        result.setSuccess(true);
        result.setResult(new Page<cn.jantd.modules.activiti.entity.ProcessDefinition>().setRecords(definitionList).setTotal(count));
        return result;
    }

    /**
     * 定义的全部列表
     */
    @ResponseBody
    @GetMapping(value = "definition/all")
    public Object definitionAllList(Model model) {
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().desc();
        if (model != null) {
            if (!StringUtils.isEmpty(model.getCategory())) {
                definitionQuery.processDefinitionCategory(model.getCategory());
            }
            if (!StringUtils.isEmpty(model.getName())) {
                definitionQuery.processDefinitionName("%" + model.getName() + "%");

            }
        }
        List<org.activiti.engine.repository.ProcessDefinition> list = definitionQuery.list();

        List<cn.jantd.modules.activiti.entity.ProcessDefinition> definitionList = new ArrayList<>();
        list.forEach(mo -> definitionList.add(new cn.jantd.modules.activiti.entity.ProcessDefinition(mo)));
        Result<List> result = new Result<List>();
        result.setResult(definitionList);
        return result;
    }

    @ResponseBody
    @PostMapping("add")
    public Result add(@RequestBody ProcessInfo process) {
        if (process == null) {
            return Result.error("获取数据失败");
        }
        LoginUser user = CommonUtil.getUser();
//        Model model = repositoryService.getModel(process.getModelId());
//        process.setModelName(model.getName());
//        process.setModelKey(model.getKey());
//        if(null == process.getProcessDefinitionId()) {
//            ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(model.getKey()).latestVersion().singleResult();
//            process.setProcessDefinitionId(definition.getId());
//        }
        process.setUserId(user.getId());
        process.setUserName(user.getUsername());
        process.setCreateTime(new Date());
        process.setRealBeginTime(new Date());
        process.setCreateBy(user.getId());
        process.setStatus(ProcessInfo.status_draft);
        processService.save(process);


        Map<String, Object> variables = new HashMap<>();
        variables.put(ProcessInfo.variables_process_info, process);
        variables.put(ProcessInfo.variables_owner, user.getId());
        ProcessInstance instance = runtimeService.startProcessInstanceById(process.getProcessDefinitionId(), variables);
        process.setStatus(ProcessInfo.status_submit);
        process.setProcessInstanceId(instance.getId());
        processService.updateById(process);

        Result result = new Result();
        result.setMessage("申请成功");
        return result;
    }


    /**
     * @Author: 风中的那朵云
     * @Description: 添加任务基本信息
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @ResponseBody
    @PostMapping("addTaskInfo")
    public Result addTaskInfo(@RequestBody ProcessInfo process) {
        if (process == null) {
            return Result.error("获取数据失败");
        }
        LoginUser user = CommonUtil.getUser();
        process.setUserId(user.getId());
        process.setUserName(user.getUsername());
        process.setCreateTime(new Date());
        process.setCreateBy(user.getId());
        process.setStatus(ProcessInfo.status_draft);
        processService.save(process);
        Result result = new Result();
        result.setMessage("添加成功");
        return result;
    }

    /**
     * @Description: 修改任务基本信息
     */
    @ResponseBody
    @PutMapping(value = "edit")
    public Result<ProcessInfo> edit(@RequestBody JSONObject jsonObject) {
        Result<ProcessInfo> result = new Result<>();
        ProcessInfo process = processService.getById(jsonObject.getString("id"));
        System.out.println("看看输出的process是什么：+++++++" + process.getId() + process.getDepartment());
        try {
            if (process == null) {
                result.error500("未找到对应实体");
            } else {
                ProcessInfo processInfo = JSON.parseObject(jsonObject.toJSONString(), ProcessInfo.class);
                processInfo.setUpdateTime(new Date());
                processInfo.setStatus(ProcessInfo.status_draft);
                boolean ok = processService.updateById(processInfo);

                if (ok) {
                    result.success("修改成功！");
                }
            }
        } catch (Exception e) {
            result.error500("操作失败");
        }
        return result;

    }


    @ResponseBody
    @DeleteMapping("delete")
    public Result delete(String id) {
        ProcessInfo leave = processService.getById(id);
        runtimeService.deleteProcessInstance(leave.getProcessInstanceId(), "");//todo
        processService.removeById(id);
        Result result = new Result();
        result.setMessage("撤销成功");
        return result;
    }

    @ResponseBody
    @PutMapping("updateStatus/{id}")
    public Result updateStatus(@PathVariable String id) {//not use
        ProcessInfo processInfo = processService.getById(id);
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInfo.getProcessInstanceId()).singleResult();
        if (null == instance) {
            processInfo.setRealEndTime(new Date());
        }
        int status = null == instance ? ProcessInfo.status_pass : ProcessInfo.status_submit;
        processInfo.setStatus(status);
        processService.updateById(processInfo);
        return new Result();
    }


    /**
     * @Author: 风中的那朵云
     * @Description: 流程规划
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @ResponseBody
    @PostMapping("flowPlan")
    public Result flowPlan(@RequestBody ProcessInfo process) {
        if (process == null) {
            return Result.error("获取数据失败");
        }
        LoginUser user = CommonUtil.getUser();

        process.setUserId(user.getId());
        process.setUserName(user.getUsername());
        process.setCreateTime(new Date());
        process.setCreateBy(user.getId());
        process.setStatus(ProcessInfo.status_draft);
        processService.updateById(process);

        Result result = new Result();
        result.setMessage("申请成功");
        return result;
    }

    /*   *//**
     * @Author: 风中的那朵云
     * @Description: 流程启动
     * @Date: 2020/5/6
     * @Version: 1.0
     *//*
    @ResponseBody
    @PostMapping("taskStart")
    public Result taskStart(@RequestBody ProcessInfo process) {
        if (process == null) {
            return Result.error("获取数据失败");
        }
        //判断任务是否指定人员
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().processDefinitionKey(process.getModelKey()).orderByProcessDefinitionVersion().desc().list();
        System.out.println("看看任务是什么：+++++++1111" + list.get(0).getName() + list.get(0).getKey());
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(list.get(0).getId());
        List<ActivityImpl> activitiList = def.getActivities();
        Result result = new Result();

        LoginUser user = CommonUtil.getUser();

        process.setUserId(user.getId());
        process.setUserName(user.getUsername());
        process.setCreateTime(new Date());
        process.setCreateBy(user.getId());

        Map<String, Object> variables = new HashMap<>();
        variables.put(ProcessInfo.variables_process_info, process);
        variables.put(ProcessInfo.variables_owner, user.getId());
        ProcessInstance instance = runtimeService.startProcessInstanceById(process.getProcessDefinitionId(), variables);
        process.setStatus(ProcessInfo.status_submit);
        process.setProcessInstanceId(instance.getId());
        processService.updateById(process);
        //通过Key找到模型
        ActModel model = modelService.selectByModel(process.getModelId());
        String str = model.getMetaInfo();
        JSONObject o = (JSONObject) JSONObject.parse(str);
        o.put("modelstatus", "1");
        modelService.updateByKey(JSONObject.toJSONString(o), model.getId());

        //节点用户插入临时表act_ru_identitylink_join
        for (ActivityImpl ai : activitiList) {
            if (ai.getProperty("type").equals("userTask")) {
                TaskDefinition taskDefinition = (TaskDefinition) ai.getProperty("taskDefinition");
//                if (ai.getProperty("name") == null) {
//                    result.setMessage("任务节点未指定名称");
//                    return result;
//                }
//               if (taskDefinition.getAssigneeExpression() == null && taskDefinition.getCandidateGroupIdExpressions().size() == 0 && taskDefinition.getCandidateUserIdExpressions().size() == 0) {
//                    result.setMessage(ai.getProperty("name") + "任务节点未指定人员");
//                    return result;
//                }
                if (taskDefinition.getAssigneeExpression() != null) {
                    IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                    identitylinkUser.setUserId(taskDefinition.getAssigneeExpression().toString());
                    identitylinkUser.setProcInstId(instance.getId());
                    identitylinkService.save(identitylinkUser);
                } else if (taskDefinition.getCandidateGroupIdExpressions().size() > 0) {
                    QueryWrapper<ActIdMembership> infoQueryWrapper = new QueryWrapper<>();
                    infoQueryWrapper
                            .eq("GROUP_ID_", taskDefinition.getCandidateGroupIdExpressions().toString().substring(1, taskDefinition.getCandidateGroupIdExpressions().toString().length() - 1));  //eq的作用是比较等于
                    List<ActIdMembership> actIdMemberships = iActIdMembershipService.list(infoQueryWrapper);
                    for(int i =0;i<actIdMemberships.size();i++){
                        IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                        identitylinkUser.setUserId(actIdMemberships.get(i).getUserId());
                        identitylinkUser.setProcInstId(instance.getId());
                        identitylinkService.save(identitylinkUser);
                    }
                } else if (taskDefinition.getCandidateUserIdExpressions().size() > 0) {
                    for(Expression UserId : taskDefinition.getCandidateUserIdExpressions()){
                        IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                        identitylinkUser.setUserId(UserId.toString());
                        identitylinkUser.setProcInstId(instance.getId());
                        identitylinkService.save(identitylinkUser);
                    }
                }
            }
        }

        result.setMessage("启动成功");
        return result;
    }*/


    /**
     * @Author: 风中的那朵云
     * @Description: 流程启动
     * @Date: 2020/5/6
     * @Version: 1.0
     */
    @ResponseBody
    @PostMapping("taskStart")
    public Result taskStart(@RequestBody ProcessInfo process) throws XMLStreamException {
        if (process == null) {
            return Result.error("获取数据失败");
        }
        //判断任务是否指定人员
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().processDefinitionKey(process.getModelKey()).orderByProcessDefinitionVersion().desc().list();
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(list.get(0).getId());
        List<ActivityImpl> activitiList = def.getActivities();
        Result result = new Result();

        LoginUser user = CommonUtil.getUser();

        process.setUserId(user.getId());
        process.setUserName(user.getUsername());
        process.setCreateTime(new Date());
        process.setCreateBy(user.getId());

        Map<String, Object> variables = new HashMap<>();
        variables.put(ProcessInfo.variables_process_info, process);
        variables.put(ProcessInfo.variables_owner, user.getId());
        ProcessInstance instance = runtimeService.startProcessInstanceById(process.getProcessDefinitionId(), variables);
        process.setStatus(ProcessInfo.status_submit);
        process.setProcessInstanceId(instance.getId());
        /*  processService.updateById(process);*/
        processService.updateForName(process);
        //通过modelId获取到对应的activityId
        /*  List<TaskFileType> taskFileTypes=iTaskFileTypeService.getByModelId(process.getModelId());*/
        QueryWrapper<ProcessInfo> processInfoQueryWrapper = new QueryWrapper<>();
        processInfoQueryWrapper
                .eq("process_instance_id", instance.getProcessInstanceId());  //eq的作用是比较等于
        ProcessInfo processInfo = processService.getOne(processInfoQueryWrapper);

        QueryWrapper<TaskFileType> taskFileTypeQueryWrapper = new QueryWrapper<>();


        List<TaskFileType> tasks = iTaskFileTypeService.list(taskFileTypeQueryWrapper);


        //通过Key找到模型
        ActModel model = modelService.selectByModel(process.getModelId());
        String str = model.getMetaInfo();
        JSONObject o = (JSONObject) JSONObject.parse(str);
        o.put("modelstatus", "1");
        modelService.updateByKey(JSONObject.toJSONString(o), model.getId());
        byte[] bytes = repositoryService.getModelEditorSource(model.getId());

        if (bytes == null) {
            return Result.error("模型为空");
        }
        BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(XMLInputFactory.newInstance().createXMLStreamReader((new ByteArrayInputStream(bytes))));
        if (bpmnModel.getProcesses().size() == 0) {
            return Result.error("数据不符合要求!");
        }
        List elements = (ArrayList) bpmnModel.getProcesses().get(0).getFlowElements();
        for (int i = 0; i < elements.size(); i++) {
            if (elements.get(i) instanceof UserTask) {
                if (((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskStartTime") == null || ((ExtensionAttribute) ((ArrayList) ((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskStartTime")).get(0)).getValue().equals("Invalid date")) {
                    return Result.error(((UserTask) elements.get(i)).getName() + "开始时间不符合要求!");
                } else if (((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskEndTime") == null || ((ExtensionAttribute) ((ArrayList) ((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskEndTime")).get(0)).getValue().equals("Invalid date")) {
                    return Result.error(((UserTask) elements.get(i)).getName() + "结束时间不符合要求!");
                } else if (((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("assignee")) == null
                        && ((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateUsers")) == null
                        && ((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateGroups")) == null) {
                    return Result.error(((UserTask) elements.get(i)).getName() + "没有指定人员!");
                } else if (((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("assignee")) != null) {
                    if (((ExtensionAttribute) ((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("assignee")).get(0)).getValue().equals("")) {
                        return Result.error(((UserTask) elements.get(i)).getName() + "没有指定人员!");
                    }
                } else if (((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateUsers")) != null) {
                    if (((ExtensionAttribute) ((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateUsers")).get(0)).getValue().equals("")) {
                        return Result.error(((UserTask) elements.get(i)).getName() + "没有指定人员!");
                    }
                } else if (((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateGroups")) != null) {
                    if (((ExtensionAttribute) ((ArrayList) ((LinkedHashMap) ((UserTask) elements.get(i)).getAttributes()).get("candidateGroups")).get(0)).getValue().equals("")) {
                        return Result.error(((UserTask) elements.get(i)).getName() + "没有指定人员!");
                    }
                }
                if (((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskStartTime") != null) {
                    UpdateWrapper<TaskFileType> taskFileTypeWrapper = new UpdateWrapper<>();
                    taskFileTypeWrapper.eq("activity_id", ((UserTask) elements.get(i)).getId());
                    TaskFileType taskFileType = new TaskFileType();
                    String theStartTime = ((ExtensionAttribute) ((ArrayList) ((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskStartTime")).get(0)).getValue();

                    SimpleDateFormat dateFormat = new SimpleDateFormat();
                    dateFormat.applyPattern("yyyy-mm-dd");
                    try {
                        taskFileType.setStartTime(dateFormat.parse(theStartTime));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    iTaskFileTypeService.update(taskFileType, taskFileTypeWrapper);
                }
                if (((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskEndTime") != null) {
                    UpdateWrapper<TaskFileType> taskFileTypeWrapper = new UpdateWrapper<>();
                    taskFileTypeWrapper.eq("activity_id", (Object) ((UserTask) elements.get(i)).getId());
                    TaskFileType taskFileType = new TaskFileType();
                    String theEndTime = ((ExtensionAttribute) ((ArrayList) ((HashMap) ((UserTask) elements.get(i)).getAttributes()).get("taskEndTime")).get(0)).getValue();
                    SimpleDateFormat dateFormat = new SimpleDateFormat();
                    dateFormat.applyPattern("yyyy-mm-dd");
                    try {
                        taskFileType.setEndTime(dateFormat.parse(theEndTime));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    iTaskFileTypeService.update(taskFileType, taskFileTypeWrapper);
                }
                if (((UserTask) elements.get(i)).getName() != null) {
                    UpdateWrapper<TaskFileType> taskFileTypeWrapper = new UpdateWrapper<>();
                    taskFileTypeWrapper.eq("activity_id", ((UserTask) elements.get(i)).getId());
                    TaskFileType taskFileType = new TaskFileType();
                    taskFileType.setTaskName(((UserTask) elements.get(i)).getName());
                    iTaskFileTypeService.update(taskFileType, taskFileTypeWrapper);
                }
            }
        }
        //节点用户插入临时表act_ru_identitylink_join
        for (ActivityImpl ai : activitiList) {
            if (ai.getProperty("type").equals("userTask")) {
                TaskDefinition taskDefinition = (TaskDefinition) ai.getProperty("taskDefinition");
//                if (ai.getProperty("name") == null) {
//                    result.setMessage("任务节点未指定名称");
//                    return result;
//                }
//               if (taskDefinition.getAssigneeExpression() == null && taskDefinition.getCandidateGroupIdExpressions().size() == 0 && taskDefinition.getCandidateUserIdExpressions().size() == 0) {
//                    result.setMessage(ai.getProperty("name") + "任务节点未指定人员");
//                    return result;
//                }
   /*             taskFileTypeQueryWrapper
                        .eq("definition_id", instance.getProcessDefinitionId())
                        .eq("activity_id", instance.getActivityId())
                        .eq("model_id", processInfo.getModelId());
                TaskFileType taskFileType = iTaskFileTypeService.getOne(taskFileTypeQueryWrapper);
                System.out.println("查看一下这个的值是什么：++"+taskFileType.getActivityId());*/
    /*            QueryWrapper<IdentitylinkUser> identitylinkUserQueryWrapper = new QueryWrapper<>();
                identitylinkUserQueryWrapper
                        .eq(.getActivityId(),ai.getId());*/

                if (taskDefinition.getAssigneeExpression() != null) {
                    IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                    identitylinkUser.setUserId(taskDefinition.getAssigneeExpression().toString());
                    identitylinkUser.setProcInstId(instance.getId());
                    identitylinkUser.setActivityId(ai.getId());
                    identitylinkService.save(identitylinkUser);
                } else if (taskDefinition.getCandidateGroupIdExpressions().size() > 0) {
                    QueryWrapper<ActIdMembership> infoQueryWrapper = new QueryWrapper<>();
                    infoQueryWrapper
                            .eq("GROUP_ID_", taskDefinition.getCandidateGroupIdExpressions().toString().substring(1, taskDefinition.getCandidateGroupIdExpressions().toString().length() - 1));  //eq的作用是比较等于
                    List<ActIdMembership> actIdMemberships = iActIdMembershipService.list(infoQueryWrapper);
                    for (int i = 0; i < actIdMemberships.size(); i++) {
                        IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                        identitylinkUser.setUserId(actIdMemberships.get(i).getUserId());
                        identitylinkUser.setProcInstId(instance.getId());
                        identitylinkUser.setActivityId(ai.getId());
                        identitylinkService.save(identitylinkUser);
                    }
                } else if (taskDefinition.getCandidateUserIdExpressions().size() > 0) {
                    for (Expression UserId : taskDefinition.getCandidateUserIdExpressions()) {
                        IdentitylinkUser identitylinkUser = new IdentitylinkUser();
                        identitylinkUser.setUserId(UserId.toString());
                        identitylinkUser.setProcInstId(instance.getId());
                        identitylinkUser.setActivityId(ai.getId());
                        identitylinkService.save(identitylinkUser);
                    }
                }
            }
        }

        result.setMessage("启动成功");
        return result;
    }
}
